package sz.szsmk.citizencard.ui.dzsmkavtivity;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.dialog.GestureDialog;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryAllCardFuncRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.ValidCardAuthorizationRes;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.ElecCitizenCardMvpView;
import sz.szsmk.citizencard.mvp.GestureMvpView;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.ElecCitizenCardPresenter;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.GesturePresenter;
import sz.szsmk.citizencard.ui.adapter.DzsmkInfoAdapter;
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean;
import sz.szsmk.citizencard.ui.newversion.activity.ScanQRCodeActivity;
import sz.szsmk.citizencard.ui.newversion.config.Constants;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.Px2Dp;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.widget.MyExpandableListView;
import sz.szsmk.citizencard.widget.PagerSlidingTabStrip;
import sz.szsmk.citizencard.widget.PersonalViewpager;

/**
 * 电子市民卡首页
 */
@Route("elecCitizenCard")
public class ElecCitizenCardActivity extends AppBaseActivity
        implements ElecCitizenCardMvpView, GestureMvpView, ExpandableListView.OnGroupExpandListener, ExpandableListView.OnChildClickListener {
    PagerSlidingTabStrip tabStrip;
    PersonalViewpager viewPager;
    ScrollView scrollView;
    TextView name;
    TextView idCard;
    TextView cardNo;
    ImageView openGesture;
    @Inject
    ElecCitizenCardPresenter elecCitizenCardPresenter;
    @Inject
    GesturePresenter gesturePresenter;
    LinearLayout dzsmkLl1;
    LinearLayout dzsmkLl2;
    LinearLayout dzsmkLl3;
    TextView line1;
    TextView line2;
    TextView line3;
    RecyclerView cardRv;
    private String[] mPagerTitle = {"全部", "市民卡信息", "完善信息"};
    private ArrayList<MyExpandableListView> mListViewList = new ArrayList<>();
    private ArrayList<MyAdapter> adapters = new ArrayList<>();
    private DzsmkInfoAdapter dzsmkInfoAdapter;
    private List<QueryAllCardFuncRes.CardFunctionInforsBean> cardFunctionInfors = new ArrayList<>();
    private List<QueryAllCardFuncRes.CardFunctionInforsBean> baseInfors = new ArrayList<>();
    private List<QueryAllCardFuncRes.CardFunctionInforsBean> otherInfors = new ArrayList<>();
    private List<ValidCardAuthorizationRes.CardAuthrationInforsBean> infors;
    private AppHomeCardBean homeCardBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent().inject(this);
        setContentView(R.layout.qr_activity_elec_citizen_card);
        initView();
        ImmersionBar.with(this).reset()
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0f)
                .statusBarColor(R.color.white).init();

        final String access_token = ACache.get(this).getAsString("access_token");
        if ("1".equals(Constant.isOpen)) {
            openGesture.setImageDrawable(getResources().getDrawable(R.mipmap.icon_ges_password));
        } else {
            openGesture.setImageDrawable(getResources().getDrawable(R.mipmap.gesture_not_open));
        }
        elecCitizenCardPresenter.validCardAuthorization();
        elecCitizenCardPresenter.queryCardFunc();
        elecCitizenCardPresenter.selectUserAuth();

        //埋点
        elecCitizenCardPresenter.userBehaviorBrowse();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        cardRv.setLayoutManager(linearLayoutManager);
        dzsmkInfoAdapter = new DzsmkInfoAdapter(this);
        dzsmkInfoAdapter.GhfOnClick(new DzsmkInfoAdapter.GhfInterface() {
            @Override
            public void onClick() {
                elecCitizenCardPresenter.getGetOrderId("ghf", "ghf");
            }
        });

        dzsmkInfoAdapter.setBaseInterface(new DzsmkInfoAdapter.BaseInterface() {
            @Override
            public void onClick(View view, String url, String syslabl, int need_header) {
                if (url.equals("ghf")) {
                    elecCitizenCardPresenter.getExtent(url);
                }
            }
        });
        cardRv.setAdapter(dzsmkInfoAdapter);

        for (int i = 0; i < mPagerTitle.length; i++) {
            MyExpandableListView list = new MyExpandableListView(this);
            list.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT));
            MyAdapter myAdapter = new MyAdapter();
            adapters.add(myAdapter);
            list.setAdapter(myAdapter);
            list.setOnGroupExpandListener(this);
            list.setGroupIndicator(null);
            list.setOnChildClickListener(this);
            list.expandGroup(0);
            mListViewList.add(list);
        }
        viewPager.setAdapter(new MyPagerAdapter());
        tabStrip.setBackgroundColor(Color.parseColor("#ffffff"));
        tabStrip.setIndicatorHeight(3);
        tabStrip.setIndicatorColor(Color.parseColor("#FF00AAFF"));
        tabStrip.setTextSize(Px2Dp.sp2px(this, 15));
        tabStrip.setTextColor(Color.parseColor("#333333"));
        tabStrip.setDividerColor(Color.parseColor("#ffffff"));
        tabStrip.setShouldExpand(true);
        tabStrip.setViewPager(viewPager);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 切换到当前页面，重置高度
                viewPager.requestLayout();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        elecCitizenCardPresenter.firstSearchUserLevel();
    }


    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.open_gesture) {
            if ("1".equals(Constant.isOpen)) {
                final GestureDialog gestureDialog = new GestureDialog(this, "是否关闭密码保护", "关闭后，再次进入电子市民卡没有手势密码保护哦！");
                gestureDialog.setOnCancelClickListener(new GestureDialog.OnCancelClickListener() {
                    @Override
                    public void onCancelClick() {
                        gestureDialog.dismiss();
                    }
                });
                gestureDialog.setOnOkClickListener(new GestureDialog.OnOkClickListener() {
                    @Override
                    public void onOkClick() {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", "elecCitizenCard");
                        bundle.putBoolean("isNeedVaild", true);
                        bundle.putInt("intotype", 1);
                        JumpUtils.jumptoNatvie(ElecCitizenCardActivity.this, "gestureLoginActivity", 0, bundle);
                    }
                });
                gestureDialog.show();
            } else {
                final GestureDialog gestureDialog = new GestureDialog(this);
                gestureDialog.setOnCancelClickListener(new GestureDialog.OnCancelClickListener() {
                    @Override
                    public void onCancelClick() {
                        gestureDialog.dismiss();
                    }
                });
                gestureDialog.setOnOkClickListener(new GestureDialog.OnOkClickListener() {
                    @Override
                    public void onOkClick() {
                        if ("0".equals(Constant.isOpen)) {
                            JumpUtils.jump(ElecCitizenCardActivity.this, "gesPasswordSettingActivity", 0);
                        } else {
                            Bundle bundle = new Bundle();
                            bundle.putString("url", "elecCitizenCard");
                            bundle.putBoolean("isNeedVaild", true);
                            JumpUtils.jumptoNatvie(ElecCitizenCardActivity.this, "gestureLoginActivity", 0, bundle);
                        }
                    }
                });
                gestureDialog.show();
            }
        } else if (id == R.id.erweima) {
            Bundle bundle = new Bundle();
            bundle.putString(ScanQRCodeActivity.SCAN_TYPE, ScanQRCodeActivity.ID_CODE);
            JumpUtils.jumptoNatvie(mContext, Constants.QRCODEACTIVITY, 0, bundle);
        } else if (id == R.id.dzsmk_ll1) {
            setViewGone();
            line1.setVisibility(View.VISIBLE);

            dzsmkInfoAdapter.setViewData(cardFunctionInfors);
            dzsmkInfoAdapter.notifyDataSetChanged();
        } else if (id == R.id.dzsmk_ll2) {
            setViewGone();
            line2.setVisibility(View.VISIBLE);
            dzsmkInfoAdapter.setViewData(otherInfors);
            dzsmkInfoAdapter.notifyDataSetChanged();
        } else if (id == R.id.dzsmk_ll3) {
            setViewGone();
            line3.setVisibility(View.VISIBLE);
            dzsmkInfoAdapter.setViewData(baseInfors);
            dzsmkInfoAdapter.notifyDataSetChanged();
        }
    }

    private void setViewGone() {

        line1.setVisibility(View.GONE);
        line2.setVisibility(View.GONE);
        line3.setVisibility(View.GONE);
    }

    @Override
    public void firstSearchUserLevelSucc(AppHomeCardBean response) {
        homeCardBean = response;
        if (!StringUtils.isBlank(response.getCustName())) {
            name.setText(response.getCustName());
        }
        if (!StringUtils.isBlank(response.getEcityCardNo()) && response.getEcityCardNo().length() > 4) {
//            cardNo.setText(response.getEcityCardNo().substring(0, 4) +
//                    " **** " + response.getEcityCardNo().substring(
//                    response.getEcityCardNo().length() - 4,
//                    response.getEcityCardNo().length()));
            cardNo.setText(response.getEcityCardNo());
        }
        if (!StringUtils.isBlank(response.getIdCard()) && response.getIdCard().length() > 4) {
            idCard.setText(response.getIdCard().substring(0, 4) +
                    " **** **** ** " + response.getIdCard().substring(14,
                    response.getIdCard().length()));
        }
    }

    @Override
    public void firstSearchUserLevelFail() {

    }

    @Override
    public void queryCardFuncSucc(QueryAllCardFuncRes response) {
        cardFunctionInfors = response.getCardFunctionInfors();
        for (int i = 0; i < cardFunctionInfors.size(); i++) {
            QueryAllCardFuncRes.CardFunctionInforsBean bean = cardFunctionInfors.get(i);
            if (bean.getFuncName().equals("桂花分") || bean.getFuncName().equals("社保") || bean.getFuncName().equals("公积金")) {
                baseInfors.add(bean);
            } else {
                otherInfors.add(bean);
            }
        }
        dzsmkInfoAdapter.setViewData(response.getCardFunctionInfors());
        dzsmkInfoAdapter.notifyDataSetChanged();
    }

    @Override
    public void queryCardFuncFail(QueryAllCardFuncRes response) {
        Toast.makeText(mContext, response.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void selectUserAuthSucc(SeleciUserAuthRes response) {
        dzsmkInfoAdapter.setAuthInfos(response.getAuthTypeList());
        dzsmkInfoAdapter.notifyDataSetChanged();
    }


    @Override
    public void selectUserAuthFail() {

    }

    @Override
    public void getExtentSucc(GetOrderOpenidRes response, String url) {
        if (url.equals("ghf")) {
            String path = Constant.SZ_URL +"?"+ response.getExtend();
            Bundle bundle = new Bundle();
            bundle.putString("url", path);
            bundle.putString(Constant.TITLE, "桂花分");
            JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
        }
    }

    @Override
    public void validCardAuthorizationSucc(ValidCardAuthorizationRes response) {

        //autype:1.休闲年卡 2.体育惠民3.文化消费
        //isAuth:0.不存在1.已授权2.未授权且有多张休闲年卡
        infors = response.getCardAuthrationInfors();
        dzsmkInfoAdapter.setXXnkAuth(infors);
        dzsmkInfoAdapter.notifyDataSetChanged();
    }

    @Override
    public void validCardAuthorizationFail(ValidCardAuthorizationRes response) {

    }

    @Override
    public void getGetOrderIdSucc(GetOrderOpenidRes response, String s, String type) {
        if (type.equals("ghf")) {
            //跳转桂花分

//            String url = Constant.WHXFTEST_URL + "portal/osmanthus/osmanthus_index.html?" + response.getExtend();

            String url = Constant.SZ_URL +"?"+ response.getExtend();
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString(Constant.TITLE, "桂花分");
            JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
        }
    }

    @Override
    public void getGetOrderIdFail() {

    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        return false;
    }

    @Override
    public void onGroupExpand(int groupPosition) {

    }

    @Override
    public void success() {
        Constant.isOpen = "2";
        openGesture.setImageDrawable(getResources().getDrawable(R.mipmap.gesture_not_open));
    }

    @Override
    public void fail() {
        Toast.makeText(this, "手势密码没有关闭成功，请重新再试。", Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if ("1".equals(Constant.isOpen)) {
            openGesture.setImageDrawable(getResources().getDrawable(R.mipmap.icon_ges_password));
        } else {
            openGesture.setImageDrawable(getResources().getDrawable(R.mipmap.gesture_not_open));
        }

        elecCitizenCardPresenter.selectUserAuth();
    }

    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return mPagerTitle.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mListViewList.get(position));
            return mListViewList.get(position);
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return mPagerTitle[position];
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mListViewList.get(position));
        }

    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{elecCitizenCardPresenter};
    }

    @Override
    protected CharSequence getTopTitle() {
        return "电子市民卡";
    }

    public class MyAdapter extends BaseExpandableListAdapter {


        @Override
        public int getGroupCount() {
            return 3;
//            return list == null || list.size() == 0 ? 0 : list.size();
        }

        @Override
        public int getChildrenCount(int i) {
            return 3;
//            return list == null || list.size() == 0 || list.get(i).getItlList() == null || list.get(i).getItlList().size() == 0 ? 0 : list.get(i).getItlList().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return null;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return null;
        }

        @Override
        public long getGroupId(int i) {
            return i;
        }

        @Override
        public long getChildId(int i, int i1) {
            return i;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public int getChildTypeCount() {
            return 3;
//            return list == null || list.size() == 0 ? 0 : list.size();
        }

        @Override
        public int getChildType(int groupPosition, int childPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            ViewHolder2 holder = null;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_elec_card, parent, false);
                CardView view = convertView.findViewById(R.id.card_cv);

                holder = new ViewHolder2(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder2) convertView.getTag();
            }
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_bank_list, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }

    }

    class ViewHolder2 {

        ViewHolder2(View view) {
        }
    }

    class ViewHolder {

        ViewHolder(View view) {
        }
    }


    private void initView(){
        tabStrip = findViewById(R.id.tabStrip);
        viewPager= findViewById(R.id.viewPager);
        scrollView= findViewById(R.id.scroll);
        name= findViewById(R.id.name);
        idCard= findViewById(R.id.id_card);
        cardNo= findViewById(R.id.card_no);
        openGesture= findViewById(R.id.open_gesture);

        dzsmkLl1= findViewById(R.id.dzsmk_ll1);
        dzsmkLl2= findViewById(R.id.dzsmk_ll2);
        dzsmkLl3= findViewById(R.id.dzsmk_ll3);
        line1= findViewById(R.id.line1);
        line2= findViewById(R.id.line2);
        line3= findViewById(R.id.line3);
        cardRv= findViewById(R.id.card_rv);

        openGesture.setOnClickListener(this::onClick);
        findViewById(R.id.erweima).setOnClickListener(this::onClick);
        dzsmkLl1.setOnClickListener(this::onClick);
        dzsmkLl2.setOnClickListener(this::onClick);
        dzsmkLl3.setOnClickListener(this::onClick);



    }
}
